package org.skydiveapphd;

import java.text.MessageFormat;

import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.LogbookHistory;
import org.skydiveapplibrary.data.Settings;
import org.skydiveapplibrary.data.UnitOfMeasure;
import org.skydiveapplibrary.repository.LogbookHistoryRepository;
import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.ui.FormatUtility;
import org.skydiveapplibrary.ui.FreefallTimeDialog;
import org.skydiveapplibrary.ui.NumberDialog;
import org.skydiveapplibrary.ui.FreefallTimeDialog.OnFreefallTimeSetListener;
import org.skydiveapplibrary.ui.NumberDialog.OnNumberSetListener;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SettingsActivity extends Fragment
{
	// repositories
	private LogbookHistoryRepository historyRepository;
	private SettingsRepository settingsRepository;
	
	// listeners
	private OnClickListener freefallTimeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showFreefallTimeDialog();
		}
	};
	private OnClickListener cutawayEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showCutawayDialog();
		}
	};
	private OnClickListener exitAltitudeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showExitAltitudeDialog();
		}
	};
	private OnClickListener deploymentAltitudeEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showDeploymentAltitudeDialog();
		}
	};

	private OnFreefallTimeSetListener freefallTimeSetListener = new OnFreefallTimeSetListener()
	{
		@Override
		public void onFreefallTimeSet(FreefallTimeDialog dialog, int freefallTime)
		{
			updateFreefallTime(freefallTime);
		}
	};
	private OnNumberSetListener cutawaySetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateCutaways(number);
		}
	};
	private OnNumberSetListener exitAltitudeSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateExitAltitude(number);
		}
	};
	private OnNumberSetListener deploymentAltitudeSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			updateDeploymentAltitude(number);
		}
	};
	private OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener()
	{
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked)
		{
			handleUnitOfMeasureSelection((CheckBox)buttonView, isChecked);	
		}
	};
	private OnClickListener backListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
	    	// finish
			getFragmentManager().popBackStack();
		}
	};

	@Override 
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		historyRepository = new LogbookHistoryRepository(getActivity());
		settingsRepository = new SettingsRepository(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{	
	    // Inflate the layout for this fragment
	    return inflater.inflate(R.layout.settings_view, container, false);   	
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		// init header
		ImageButton backButton = (ImageButton) getActivity().findViewById(R.id.SettingsBackButton);
		backButton.setOnClickListener(backListener);
		
		TextView headerText = (TextView) getActivity().findViewById(R.id.EditHeaderTextView);
		headerText.setText(R.string.settings_header);
		
		TextView freefallTimeField = (TextView) getActivity().findViewById(R.id.SettingsFreefallTimeField);
		freefallTimeField.setOnClickListener(freefallTimeEditListener);

		TextView cutawayField = (TextView) getActivity().findViewById(R.id.SettingsCutawaysField);
		cutawayField.setOnClickListener(cutawayEditListener);
		
		TextView exitAltField = (TextView) getActivity().findViewById(R.id.SettingsExitAltitudeField);
		exitAltField.setOnClickListener(exitAltitudeEditListener);
		
		TextView deplAltField = (TextView) getActivity().findViewById(R.id.SettingsDeploymentAltitude);
		deplAltField.setOnClickListener(deploymentAltitudeEditListener);

		CheckBox usUnits = (CheckBox) getActivity().findViewById(R.id.SettingsUSCheckBox);
		usUnits.setOnCheckedChangeListener(checkedChangeListener);
		
		CheckBox metricUnits = (CheckBox) getActivity().findViewById(R.id.SettingsMetricCheckBox);
		metricUnits.setOnCheckedChangeListener(checkedChangeListener);

		// init field values
		updateHistoryUI();
		updateAltitudeUI();
		// update uoms
		UnitOfMeasure uom = settingsRepository.getSettings().getUnitOfMeasure();
		usUnits.setChecked(uom == UnitOfMeasure.US);
		metricUnits.setChecked(uom == UnitOfMeasure.Metric);	

	}
	
	private void showFreefallTimeDialog()
	{
		// init dialog
		LogbookHistory history = historyRepository.getHistory();
		FreefallTimeDialog dialog = new FreefallTimeDialog(
				getActivity(),
				history.getFreefallTime(),
				freefallTimeSetListener);
		// show dialog
		dialog.show();
	}
	
	private void showCutawayDialog()
	{
		// init dialog
		LogbookHistory history = historyRepository.getHistory();
		NumberDialog dialog = new NumberDialog(
				getActivity(),
				R.string.settings_cutaways_label,
				history.getCutaways(),
				cutawaySetListener);
		// show dialog
		dialog.show();
	}
	
	private void showExitAltitudeDialog()
	{
		// init dialog
		int exitAltitude = settingsRepository.getSettings().getExitAltitude();
		NumberDialog dialog = new NumberDialog(
				getActivity(),
				R.string.settings_default_exit_altitude_label,
				exitAltitude,
				exitAltitudeSetListener);
		// show dialog
		dialog.show();
	}
	
	private void showDeploymentAltitudeDialog()
	{
		// init dialog
		int deploymentAltitude = settingsRepository.getSettings().getDeploymentAltitude();
		NumberDialog dialog = new NumberDialog(
				getActivity(),
				R.string.settings_default_deployment_altitude_label,
				deploymentAltitude,
				deploymentAltitudeSetListener);
		// show dialog
		dialog.show();
	}
	
	private void updateFreefallTime(int freefallTime)
	{
		// update history
		LogbookHistory history = historyRepository.getHistory();
		history.setFreefallTime(freefallTime);
		historyRepository.updateHistory(history);
		
		// update UI
		updateHistoryUI();
	}
	
	private void updateHistoryUI()
	{
		// get history
		LogbookHistory history = historyRepository.getHistory();
		int freefallTime = history.getFreefallTime();
		
		// format
		int hours = freefallTime / 3600;
		int secondsLeftFromHours = freefallTime % 3600;
		int minutes = secondsLeftFromHours / 60;
		int seconds = secondsLeftFromHours % 60;
		// freefall time
		TextView freefallTimeField = (TextView) getActivity().findViewById(R.id.SettingsFreefallTimeField);
		String ffTimeString = MessageFormat.format(
				getString(R.string.freefall_time_hms_format), hours, minutes, seconds);
		freefallTimeField.setText(ffTimeString);
		// cutaways
		TextView cutawayField = (TextView) getActivity().findViewById(R.id.SettingsCutawaysField);
		cutawayField.setText(FormatUtility.toNumericString(history.getCutaways()));
	}
	
	private void updateCutaways(int cutaways)
	{
		// update history
		LogbookHistory history = historyRepository.getHistory();
		history.setCutaways(cutaways);
		historyRepository.updateHistory(history);
		
		// update UI
		updateHistoryUI();
	}
	
	private void updateExitAltitude(int altitude)
	{
		// update settings
		Settings settings = settingsRepository.getSettings();
		settings.setExitAltitude(altitude);
		settingsRepository.updateSettings(settings);
		
		// update UI
		updateAltitudeUI();
	}
	
	private void updateDeploymentAltitude(int altitude)
	{
		// update settings
		Settings settings = settingsRepository.getSettings();
		settings.setDeploymentAltitude(altitude);
		settingsRepository.updateSettings(settings);
		
		// update UI
		updateAltitudeUI();
	}
	
	private void updateAltitudeUI()
	{
		Settings settings = settingsRepository.getSettings();
		// exit altitude
		TextView exitAltField = (TextView) getActivity().findViewById(R.id.SettingsExitAltitudeField);
		exitAltField.setText(FormatUtility.toNumericString(settings.getExitAltitude()));
		// deplyment altitude
		TextView deplAltField = (TextView) getActivity().findViewById(R.id.SettingsDeploymentAltitude);
		deplAltField.setText(FormatUtility.toNumericString(settings.getDeploymentAltitude()));
	}

	private void handleUnitOfMeasureSelection(CheckBox checkBox, boolean isChecked)
	{
		// get checkboxes
		CheckBox usUnits = (CheckBox) getActivity().findViewById(R.id.SettingsUSCheckBox);
		CheckBox metricUnits = (CheckBox) getActivity().findViewById(R.id.SettingsMetricCheckBox);
		
		// get settings
		Settings settings = settingsRepository.getSettings();
		
		if (checkBox == usUnits && isChecked)
		{
			// clear metric
			metricUnits.setChecked(false);
			// update settings
			settings.setUnitOfMeasure(UnitOfMeasure.US);
		}
		else if (checkBox == metricUnits && isChecked)
		{
			// clear us
			usUnits.setChecked(false);
			// update settings
			settings.setUnitOfMeasure(UnitOfMeasure.Metric);
		}
		
		// save settings
		settingsRepository.updateSettings(settings);
	}
}
